package org.jeecg.modules.demo.temple.pay.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.JxyhPayHttpRequestUtil;
import org.jeecg.common.util.JxyhPaySignatureUtil;
import org.jeecg.modules.demo.temple.order.entity.TempleActivityOrder;
import org.jeecg.modules.demo.temple.order.entity.TempleDonationOrder;
import org.jeecg.modules.demo.temple.order.service.ITempleActivityOrderService;
import org.jeecg.modules.demo.temple.order.service.ITempleDonationOrderService;
import org.jeecg.modules.demo.temple.pay.entity.TempleMerchantInfo;
import org.jeecg.modules.demo.temple.pay.service.ITempleMerchantInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
* @Description: 江西银行聚合支付
* @Author: jeecg-boot
* @Date:   2022-05-23
* @Version: V1.0
*/
@Api(tags="江西银行聚合支付")
@RestController
@RequestMapping("/temple.pay/jxyhPayContoller")
@Slf4j
public class JxyhPayController extends JeecgController<TempleMerchantInfo, ITempleMerchantInfoService> {
   @Autowired
   private ITempleMerchantInfoService templeMerchantInfoService;

    @Autowired
    private ITempleDonationOrderService templeDonationOrderService;

    @Autowired
    private ITempleActivityOrderService templeActivityOrderService;

   /**
    * 支付接结果通知
    *
    * @param req
    * @return
    */
   //@AutoLog(value = "商户信息表-分页列表查询")
   @ApiOperation(value="商户信息表-分页列表查询", notes="商户信息表-分页列表查询")
   @PostMapping(value = "/api/notify")
   public Result<IPage<TempleMerchantInfo>> notify(HttpServletRequest req) {
           log.info("contentType:"+req.getContentType());
           log.info("encoding:"+req.getCharacterEncoding());
           log.info("queryString:"+req.getQueryString());
           log.info("requestUrl:"+req.getRequestURL());

       Enumeration<String> names = req.getParameterNames();
       Map<String,String> resMap = new HashMap<String,String>();
       while(names.hasMoreElements()){
           String name = (String)names.nextElement();
           String value = req.getParameter(name);
//           if(name.equals("respmsg")){
//               try {
//                   byte source[] = value.getBytes("iso8859-1");
//                   value  = new String (source,"UTF-8");
//                   log.info("respmsg encoding:"+value);
//               }catch (UnsupportedEncodingException e){
//                   e.printStackTrace();
//               }
//           }
           resMap.put(name,value);
           log.info("name:"+name+"&value:"+value);
       }
       String orderNo = req.getParameter("orderno");
       String status = req.getParameter("status");
       String orderId ="";
       String sysOrgCode = "";
       TempleDonationOrder templeDonationOrder = null;
       TempleActivityOrder templeActivityOrder = null;
       //1.校验订单号
       if(orderNo.startsWith("D")){
           orderId = orderNo.substring(orderNo.indexOf("D") + 1);
           templeDonationOrder = templeDonationOrderService.getById(orderId);
           if(templeDonationOrder!= null) {
               sysOrgCode = templeDonationOrder.getSysOrgCode();
           }else{
               throw new RuntimeException("通知支付结果：订单号不存在:"+orderNo);
           }
       }else if(orderNo.startsWith("A")){
           orderId = orderNo.substring(orderNo.indexOf("A") + 1);
           templeActivityOrder = templeActivityOrderService.getById(orderId);
           if(templeActivityOrder!= null) {
               sysOrgCode = templeActivityOrder.getSysOrgCode();
           }else{
               throw new RuntimeException("通知支付结果：订单号不存在:"+orderNo);
           }
       }else{
           throw new RuntimeException("通知支付结果：非法订单号:"+orderNo);
       }

       //2.查询商户信息
       TempleMerchantInfo templeMerchantInfo = new TempleMerchantInfo();
       templeMerchantInfo.setSysOrgCode(sysOrgCode);
       QueryWrapper<TempleMerchantInfo> queryWrapper = QueryGenerator.initQueryWrapper(templeMerchantInfo, req.getParameterMap());
       templeMerchantInfo = templeMerchantInfoService.getOne(queryWrapper);
       String publicKey = templeMerchantInfo.getPublicKey();
       String apiKey = templeMerchantInfo.getApiKey();

        //3.验签返回报文是否合法
       JxyhPaySignatureUtil jxyhPaySignatureUtil = new JxyhPaySignatureUtil();
//       if (jxyhPaySignatureUtil.verify256Sign(resMap, publicKey, apiKey)) {
           if(orderNo.startsWith("D")){
               if(status.equals("0")){
                   templeDonationOrder.setIsPay("Y");
               }
               templeDonationOrderService.updateById(templeDonationOrder);
               log.info("D"+templeDonationOrder.getId()+"修改订单状态成功");
           }else if(orderNo.startsWith("A")){
               if(status.equals("0")){
                   templeActivityOrder.setIsPay("Y");
                   log.info("A"+templeActivityOrder.getId()+"修改订单状态成功");
               }
               templeActivityOrderService.updateById(templeActivityOrder);
           }
//       } else {
//           throw new RuntimeException("下单通知结果返回报文验签失败");
//       }

       return Result.OK("respcode=00000&respmsg=success");
   }

    public static void main(String[] args) {
       try {
           File file = new File("d://jxbank_pubkey.cert");
           CertificateFactory cf = CertificateFactory.getInstance("X.509");
           X509Certificate cert = (X509Certificate)cf.generateCertificate(new FileInputStream(file));
           PublicKey publicKey = cert.getPublicKey();
           BASE64Encoder base64Encoder = new BASE64Encoder();
           String publicKeyString = base64Encoder.encode(publicKey.getEncoded());
           System.out.println(publicKeyString);
       }catch (Exception e){
           e.printStackTrace();
       }
    }


}
